package com.seuic.hnjiningposapp.hnapps.ui.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.cardview.widget.CardView;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.TouchUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.seuic.hnjiningposapp.R;
import com.seuic.hnjiningposapp.hnapps.SquareLayout;
import com.seuic.hnjiningposapp.hnapps.base.BaseActivity;
import com.seuic.hnjiningposapp.hnapps.bean.AllDealBean;
import com.seuic.hnjiningposapp.hnapps.bean.StatisticsBean;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.ChangeFtpPp;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.ChangeMainKey;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.ChangeOperatorPp;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.DealingPopup;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.ErrorPopup;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.OperatorBInputManagerPw;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.PrintingPopup;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.StatisticsPp;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.SurePrintPopup;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.TransactionqQueryPp;
import com.seuic.hnjiningposapp.hnapps.util.GetMoneyLvUtils;
import com.seuic.hnjiningposapp.hnapps.util.HttpUtils;
import com.seuic.hnjiningposapp.hnapps.util.HttpUtilsV2;
import com.seuic.hnjiningposapp.hnapps.util.PrintUtil;
import com.seuic.posdsdk.pos_func.PosFuncs;
import com.socks.library.KLog;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 操作员业务
 */
public class OperatorBusinessActivity extends BaseActivity implements
        ChangeFtpPp.onChangeFtpCallBacl,
        OperatorBInputManagerPw.OperatorBInputManagerCallBack, SurePrintPopup.ClickCallback, StatisticsPp.queryStataDeal, TransactionqQueryPp.queryAllDeal, ErrorPopup.OnFinishCallbacked, TransactionqQueryPp.TranSQueryCallback, StatisticsPp.onStatisPrint, ChangeMainKey.onChangeMainCallBacl, ChangeOperatorPp.OnChangeOperatorPwCallBack {
    @BindView(R.id.runwater)
    SquareLayout runwater;
    @BindView(R.id.statistics)
    SquareLayout statistics;
    @BindView(R.id.change_pw)
    SquareLayout changePw;
    @BindView(R.id.change_key)
    SquareLayout changeKey;
    @BindView(R.id.home_query_layout)
    CardView homeQueryLayout;
    @BindView(R.id.ftp)
    SquareLayout ftp;
    private ChangeOperatorPp changeOperatorPp;
    private BasePopupView changeOperatorPpView;
    private StatisticsPp statisticsPp;
    private BasePopupView statisticsPpView;
    private TransactionqQueryPp transactionqQueryPp;
    private BasePopupView transactionqQueryPpView;
    private ChangeMainKey changeMainKey;
    private BasePopupView changeMainKeyView;
    private DealingPopup dealingPop;
    private BasePopupView dealingPopupView;
    private ErrorPopup errorPopup;
    private BasePopupView errorPopupPpView;
    private String alldealStarttime;
    private String alldealEndtime;
    private String alldealStatus;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");// HH:mm:ss
    //获取当前时间
    Date date = new Date(System.currentTimeMillis());
    private SurePrintPopup surePrintPop;
    private BasePopupView surePrintPopupView;
    private PrintingPopup printingPop;
    private BasePopupView printingPopupView;
    private OperatorBInputManagerPw operatorBInputManagerPw;
    private BasePopupView operatorBInputManagerPwView;
    private boolean typeftp=false;
    private ChangeFtpPp changeFtpPp;
    private BasePopupView changeFtpPpView;

    @Override
    public int initView(Bundle savedInstanceState) {
        return R.layout.activity_operator_business;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        setTitleText("操作员业务");
        findViewById(R.id.base_back_btn).setVisibility(View.INVISIBLE);
        operatorBInputManagerPw = new OperatorBInputManagerPw(this, this);
        changeFtpPp = new ChangeFtpPp(this, this);
        changeFtpPpView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(changeFtpPp);
        //主密钥
        operatorBInputManagerPwView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(operatorBInputManagerPw);

        changeMainKey = new ChangeMainKey(this, this);
        changeMainKeyView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(changeMainKey);//主密钥

        changeOperatorPp = new ChangeOperatorPp(this, this);
        changeOperatorPpView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(changeOperatorPp);
        dealingPop = new DealingPopup(this, this);
        //交易中
        dealingPopupView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(dealingPop);
        errorPopup = new ErrorPopup(this, this);
        errorPopupPpView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(errorPopup);
        //打印纸是否正常界面
        surePrintPop = new SurePrintPopup(this, this, this);
        surePrintPopupView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(surePrintPop);
        printingPop = new PrintingPopup(this, this);
        //打印中界面
        printingPopupView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(printingPop);

    }

    @Override
    public void initEvent(Bundle savedInstanceState) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.runwater, R.id.statistics, R.id.change_pw, R.id.change_key, R.id.ftp})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.runwater:
                //交易查询
                homeQueryLayout.setVisibility(View.GONE);

                queryAllDeal(simpleDateFormat.format(date), simpleDateFormat.format(date), "");
                break;
            case R.id.ftp:
                //点钞机
                homeQueryLayout.setVisibility(View.GONE);
                operatorBInputManagerPwView.show();
                typeftp =true;
                break;
            case R.id.statistics:
                homeQueryLayout.setVisibility(View.GONE);
                queryStatDeal(simpleDateFormat.format(date), simpleDateFormat.format(date), "");
                break;
            case R.id.change_pw:
                //更新密码
                homeQueryLayout.setVisibility(View.GONE);
                changeOperatorPpView.show();
                break;
            case R.id.change_key:
                homeQueryLayout.setVisibility(View.GONE);
                operatorBInputManagerPwView.show();
                //更换主密钥
                break;
        }
    }

    private void queryAllDeal(String stime, String endtime, String stutas) {

        alldealStarttime = GetMoneyLvUtils.gettimeNohour(stime);
        alldealEndtime = GetMoneyLvUtils.gettimeNohour(endtime);

        if (stutas.equals("")) {
            alldealStatus = "全部";
        } else if (stutas.equals("S")) {
            alldealStatus = "正常";
        } else if (stutas.equals("F")) {
            alldealStatus = "异常";
        }

        if (transactionqQueryPpView != null) {
            transactionqQueryPpView.dismiss();
            transactionqQueryPpView = null;
            transactionqQueryPp = null;
        }
        transactionqQueryPp = new TransactionqQueryPp(this, this, this);
        transactionqQueryPpView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(transactionqQueryPp);//本机交易查询


        showMakeHint("正在交易...");
        HttpUtilsV2.gettransactionqQuery(
                stime,
                endtime, stutas, new HttpUtilsV2.NetCallBack() {
                    @Override
                    public void onSuccess(String ServerSeqNo, String ConsumerSeqNo, JSONObject rspBody) {
                        Gson gson = new Gson();
                        List<AllDealBean> beans = gson.fromJson(rspBody.getString("resultSet"),
                                new TypeToken<ArrayList<AllDealBean>>() {
                                }.getType());
                        KLog.e(beans.size() + "size");
                        runOnUiThread(() -> {
                            dismissshowMakeHint();
                            transactionqQueryPp.setBeans(beans);
                            transactionqQueryPp.setAllEndtime(endtime);
                            transactionqQueryPp.setAllStarttime(stime);
                            transactionqQueryPp.setStatus(stutas);

                            transactionqQueryPpView.show();
                        });
                    }

                    @Override
                    public void onError(String code, String msg) {
                        showErr(msg);
                    }
                });
    }

    /**
     * 重置密码 确定输入
     * * 需要自己写参数 httputil  uiTool
     */
    @Override
    public void onchangeOpPw(String oldpw, String newpw) {
        changeOperatorPpView.dismiss();
        dealingPopupView.show();
        HttpUtilsV2.changeManangerPW(oldpw, newpw, new HttpUtilsV2.NetCallBack() {
            @Override
            public void onSuccess(String ServerSeqNo, String ConsumerSeqNo, JSONObject rspBody) {
                ToastUtils.showLong("操作成功");
                finish();
            }

            @Override
            public void onError(String code, String msg) {
                showErr(msg);
            }
        });

    }

    private void showErr(String msg) {
        runOnUiThread(() -> {
            errorPopup.setMsg(msg);
            errorPopupPpView.show();
        });
    }

    /**
     * 重置密码 退出
     */
    @Override
    public void onchangeOpPwOut() {
        finish();
    }

    /**
     * 修改主密钥 返回key1 key2
     *
     * @param key1
     * @param key2 需要自己写参数 httputil  uiTool
     */
    @Override
    public void onChangeMainok(String key1, String key2) {
        changeMainKeyView.dismiss();
        String primarySecretKey = HttpUtils.getPrimarySecretKey(key1, key2);
        KLog.e(primarySecretKey + "primarySecretKey");
        if (!TextUtils.isEmpty(primarySecretKey)) {
            SPStaticUtils.put("primarySecretKey", primarySecretKey);
            ToastUtils.showLong("修改主密钥成功");
        } else {
            ToastUtils.showLong("修改主密钥失败");
        }
        finish();

    }

    /**
     * 修改主密钥 点击了退出按钮
     */
    @Override
    public void onChangeMainout() {
        finish();
    }


    @Override
    public void finished() {
        finish();
    }

    /**
     * 交易查询
     *
     * @param starttime
     * @param endtime
     * @param status
     */
    @Override
    public void queryData(String starttime, String endtime, String status) {
        queryAllDeal(starttime, endtime, status);
    }

    /**
     * 本机交易汇总打印
     *
     * @param beans
     */

    @Override
    public void onStatisPrintto(List<StatisticsBean> beans) {
        if (beans.size() > 0) {
            PrintUtil.PAllSTATDeal(PosFuncs.getInstace(), 0, alldealStarttime, alldealEndtime, alldealStatus,
                    beans, new PrintUtil.onPrintinterface() {
                        @Override
                        public void success(String success) {
                            ToastUtils.showLong(success);
                            finish();
                        }

                        @Override
                        public void failed(String error) {
                            showErr(error);
                        }
                    });
        } else {
            ToastUtils.showLong("暂无数据");
            finish();
        }
    }

    /**
     * 交易查询 打印
     *
     * @param beans
     */
    @Override
    public void TranSQuery(List<AllDealBean> beans) {
        if (beans.size() > 0) {
            PrintUtil.PAllDeal(PosFuncs.getInstace(), 0, alldealStarttime, alldealEndtime, alldealStatus,
                    beans, new PrintUtil.onPrintinterface() {
                        @Override
                        public void success(String success) {
                            ToastUtils.showLong(success);
                            finish();
                        }

                        @Override
                        public void failed(String error) {
                            showErr(error);
                        }
                    });
        } else {
            ToastUtils.showLong("暂无数据");
            finish();
        }
    }

    /**
     * 本机交易汇总查询
     */
    @Override
    public void queryStatData(String starttime, String endtime, String status) {
        queryStatDeal(starttime, endtime, status);
    }

    private void queryStatDeal(String starttime, String endtime, String status) {
        alldealStarttime = GetMoneyLvUtils.gettimeNohour(starttime);
        alldealEndtime = GetMoneyLvUtils.gettimeNohour(endtime);

        if (status.equals("")) {
            alldealStatus = "全部";
        } else if (status.equals("S")) {
            alldealStatus = "正常";
        } else if (status.equals("F")) {
            alldealStatus = "异常";
        }


        if (statisticsPpView != null) {
            statisticsPpView.dismiss();
            statisticsPpView = null;
            statisticsPp = null;
        }
        statisticsPp = new StatisticsPp(this, this, this);
        statisticsPpView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(statisticsPp);//汇总交易

        showMakeHint("正在交易...");
        HttpUtilsV2.getStatisticsQuery(
                starttime,
                endtime, status, new HttpUtilsV2.NetCallBack() {
                    @Override
                    public void onSuccess(String ServerSeqNo, String ConsumerSeqNo, JSONObject rspBody) {
                        Gson gson = new Gson();
                        List<StatisticsBean> beans = gson.fromJson(rspBody.getString("resultSet"),
                                new TypeToken<ArrayList<StatisticsBean>>() {
                                }.getType());
                        KLog.e(beans.size() + "size");
                        runOnUiThread(() -> {
                            dismissshowMakeHint();
                            statisticsPp.setBeans(beans);
                            statisticsPp.setEndTime(endtime);
                            statisticsPp.setStartTime(starttime);
                            statisticsPp.setStatus(status);

                            statisticsPpView.show();
                        });
                    }

                    @Override
                    public void onError(String code, String msg) {
                        showErr(msg);
                    }
                });
    }

    @Override
    public void ToPrint() {

    }

    /**
     * 修改主密钥 先进行操作员严密
     *
     * @param acc
     * @param pw
     */
    @Override
    public void OperatorBInputManagerok(String acc, String pw) {
        HttpUtilsV2.getSignIn(acc, pw, new HttpUtilsV2.NetCallBack() {
            @Override
            public void onSuccess(String ServerSeqNo, String ConsumerSeqNo, JSONObject rspBody) {
                runOnUiThread(() -> {
                    operatorBInputManagerPwView.dismiss();
                    if (typeftp) {
                        KLog.e("aaaaa");
                        changeFtpPpView.show();
                    } else {
                        changeMainKeyView.show();
                    }

                });
            }

            @Override
            public void onError(String code, String msg) {
                showErr(msg);
            }
        });


    }

    @Override
    public void OperatorBInputManagerout() {
        finish();
    }

    @Override
    public void onChangeFtpok() {
        ToastUtils.showLong("点钞机设置成功");
        finish();
    }

    @Override
    public void onChangeFtpout() {
        finish();
    }
}
